package com.my.oschina.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.TextView;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.LayoutParams;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.my.oschina.R;
import com.my.oschina.app.AppContext;
import com.my.oschina.app.AppException;
import com.my.oschina.bean.Blog;
import com.my.oschina.bean.FavoriteList;
import com.my.oschina.bean.Result;
import com.my.oschina.common.StringUtils;
import com.my.oschina.common.UIHelper;

/**
 * 博客详情
 * 
 * @author liux (http://my.oschina.net/liux)
 * @version 1.0
 * @created 2012-3-21
 */
public class BlogDetailActivity extends OscBaseActivity {

	private ImageView mDocTYpe;
	private TextView mTitle;
	private TextView mAuthor;
	private TextView mPubDate;
	private TextView mCommentCount;
	private TextView abCommentText;

	private WebView mWebView;
	private Handler mHandler;
	private Blog blogDetail;
	private int blogId;

	private GestureDetector gd;
	private boolean isFullScreen;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.blog_detail);

		getSupportActionBar().setDisplayShowHomeEnabled(false);
		getSupportActionBar().setDisplayShowTitleEnabled(true);
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		setTitle(R.string.blog_detail_head_title);

		// 载入自定义的布局文件
		View customView = LayoutInflater.from(this).inflate(
				R.layout.news_detailpage_action_view, null);
		abCommentText = (TextView) customView
				.findViewById(R.id.news_detail_comment);
		// 跳转到评论页面
		abCommentText.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (blogId == 0) {
					return;
				}
				Intent intent = new Intent(BlogDetailActivity.this,
						CommentActivity.class);
				intent.putExtra("curId", blogId);
				intent.putExtra("blogType", "BlogCommentList");
				startActivity(intent);
			}
		});

		// 设置自定义布局在ActionBar上的显示位置
		ActionBar.LayoutParams lp = new ActionBar.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		lp.gravity = Gravity.RIGHT;
		getSupportActionBar().setCustomView(customView, lp);
		getSupportActionBar().setDisplayShowCustomEnabled(true);

		this.initView();
		this.initData();

		// 注册双击全屏事件
		this.regOnDoubleEvent();
	}

	/**
	 * 初始化视图控件
	 */
	private void initView() {

		blogId = getIntent().getIntExtra("blog_id", 0);

		if (blogId > 0) {
			// tempCommentKey = AppConfig.TEMP_COMMENT + "_"
			// + CommentPub.CATALOG_BLOG + "_" + blogId;
		}

		mDocTYpe = (ImageView) findViewById(R.id.blog_detail_documentType);
		mTitle = (TextView) findViewById(R.id.blog_detail_title);
		mAuthor = (TextView) findViewById(R.id.blog_detail_author);
		mPubDate = (TextView) findViewById(R.id.blog_detail_date);
		mCommentCount = (TextView) findViewById(R.id.blog_detail_commentcount);

		mWebView = (WebView) findViewById(R.id.blog_detail_webview);
		mWebView.getSettings().setSupportZoom(true);
		mWebView.getSettings().setBuiltInZoomControls(true);
		mWebView.getSettings().setDefaultFontSize(15);
		UIHelper.addWebImageShow(this, mWebView);

		mAuthor.setOnClickListener(authorClickListener);

	}

	/**
	 * 初始化控件数据
	 */
	private void initData() {

		mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				if (msg.what == 1) {
					int count = blogDetail.getCommentCount();
					int docType = blogDetail.getDocumentType();
					if (docType == Blog.DOC_TYPE_ORIGINAL) {
						mDocTYpe.setImageResource(R.drawable.widget_original_icon);
					} else if (docType == Blog.DOC_TYPE_REPASTE) {
						mDocTYpe.setImageResource(R.drawable.widget_repaste_icon);
					}

					mTitle.setText(blogDetail.getTitle());
					mAuthor.setText(blogDetail.getAuthor());
					mPubDate.setText(StringUtils.friendly_time(blogDetail
							.getPubDate()));
					mCommentCount.setText(String.valueOf(count));

					// 显示评论数
					if (count > 0) {
						abCommentText.setEnabled(true);
						abCommentText.setText(count + "评论");
					} else {
						abCommentText.setEnabled(false);
						abCommentText.setText("暂无评论");
					}

					String body = UIHelper.WEB_STYLE + blogDetail.getBody()
							+ "<div style=\"margin-bottom: 80px\" />";
					// 读取用户设置：是否加载文章图片--默认有wifi下始终加载图片
					boolean isLoadImage;
					AppContext ac = (AppContext) getApplication();
					if (AppContext.NETTYPE_WIFI == ac.getNetworkType()) {
						isLoadImage = true;
					} else {
						isLoadImage = ac.isLoadImage();
					}
					if (isLoadImage) {
						body = body.replaceAll(
								"(<img[^>]*?)\\s+width\\s*=\\s*\\S+", "$1");
						body = body.replaceAll(
								"(<img[^>]*?)\\s+height\\s*=\\s*\\S+", "$1");

						// 添加点击图片放大支持
						body = body
								.replaceAll("(<img[^>]+src=\")(\\S+)\"",
										"$1$2\" onClick=\"javascript:mWebViewImageListener.onImageClick('$2')\"");

						System.out.println(body);
					} else {
						body = body.replaceAll("<\\s*img\\s+([^>]*)\\s*>", "");
					}

					mWebView.loadDataWithBaseURL(null, body, "text/html",
							"utf-8", null);
					mWebView.setWebViewClient(UIHelper.getWebViewClient());

					// 发送通知广播
					if (msg.obj != null) {
						// UIHelper.sendBroadCast(BlogDetailActivity.this,
						// (Notice) msg.obj);
					}
				} else if (msg.what == 0) {

					UIHelper.ToastMessage(BlogDetailActivity.this,
							R.string.msg_load_is_null);
				} else if (msg.what == -1 && msg.obj != null) {

					((AppException) msg.obj).makeToast(BlogDetailActivity.this);
				}
			}
		};

		initData(blogId, false);
	}

	/**
	 * 
	 * @param blog_id
	 * @param isRefresh
	 */
	private void initData(final int blog_id, final boolean isRefresh) {

		new Thread() {
			@Override
			public void run() {
				Message msg = new Message();
				try {
					blogDetail = ((AppContext) getApplication()).getBlog(
							blog_id, isRefresh);
					msg.what = (blogDetail != null && blogDetail.getId() > 0) ? 1
							: 0;
					msg.obj = (blogDetail != null) ? blogDetail.getNotice()
							: null;
				} catch (AppException e) {
					e.printStackTrace();
					msg.what = -1;
					msg.obj = e;
				}
				mHandler.sendMessage(msg);
			}
		}.start();
	}

	private View.OnClickListener authorClickListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			UIHelper.showUserCenter(v.getContext(), blogDetail.getAuthorId(),
					blogDetail.getAuthor());
		}
	};

	/**
	 * 注册双击全屏事件
	 */
	private void regOnDoubleEvent() {
		gd = new GestureDetector(this,
				new GestureDetector.SimpleOnGestureListener() {
					@Override
					public boolean onDoubleTap(MotionEvent e) {
						isFullScreen = !isFullScreen;
						if (!isFullScreen) {
							WindowManager.LayoutParams params = getWindow()
									.getAttributes();
							params.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
							getWindow().setAttributes(params);
							getWindow()
									.clearFlags(
											WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
							getSupportActionBar().show();
						} else {
							WindowManager.LayoutParams params = getWindow()
									.getAttributes();
							params.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
							getWindow().setAttributes(params);
							getWindow()
									.addFlags(
											WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
							getSupportActionBar().hide();
						}
						return true;
					}
				});
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent event) {
		if (isAllowFullScreen()) {
			gd.onTouchEvent(event);
		}
		return super.dispatchTouchEvent(event);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getSupportMenuInflater().inflate(R.menu.menu_news_detail, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {

		if (blogDetail != null && blogDetail.getFavorite() == 1) {
			menu.findItem(R.id.menu_newsdetail_favorite).setVisible(false);
			menu.findItem(R.id.menu_newsdetail_unfavorite).setVisible(true);
		} else {
			menu.findItem(R.id.menu_newsdetail_favorite).setVisible(true);
			menu.findItem(R.id.menu_newsdetail_unfavorite).setVisible(false);
		}

		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			break;
		// 写评论
		case R.id.menu_newsdetail_write:
			finish();
			break;
		// 收藏/取消收藏
		case R.id.menu_newsdetail_favorite:
		case R.id.menu_newsdetail_unfavorite:
			if (blogId == 0 || blogDetail == null) {
				break;
			}
			final AppContext ac = (AppContext) getApplication();
			if (!ac.isLogin()) {
				Intent i = new Intent(BlogDetailActivity.this,
						LoginActivity.class);
				startActivity(i);
				break;
			}

			favoriteOrUnFavorite(ac);

			break;
		// 分享
		case R.id.menu_newsdetail_share:
			if (blogDetail == null) {
				UIHelper.ToastMessage(BlogDetailActivity.this,
						R.string.msg_read_detail_fail);
				break;
			}
			// 分享到
			UIHelper.showShareDialog(BlogDetailActivity.this,
					blogDetail.getTitle(), blogDetail.getUrl());
			break;
		// 刷新
		case R.id.menu_newsdetail_refresh:
			initData(blogId, true);
			break;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	/**
	 * 收藏/取消收藏
	 * 
	 * @param ac
	 */
	private void favoriteOrUnFavorite(final AppContext ac) {
		final int uid = ac.getLoginUid();
		final Handler handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				if (msg.what == 1) {
					Result res = (Result) msg.obj;
					if (res.OK()) {
						if (blogDetail.getFavorite() == 1) {
							blogDetail.setFavorite(0);
						} else {
							blogDetail.setFavorite(1);
						}
						// 重新保存缓存
						ac.saveObject(blogDetail, blogDetail.getCacheKey());
					}
					UIHelper.ToastMessage(BlogDetailActivity.this,
							res.getErrorMessage());
				} else {
					((AppException) msg.obj).makeToast(BlogDetailActivity.this);
				}
			}
		};

		new Thread() {
			@Override
			public void run() {
				Message msg = new Message();
				Result res = null;
				try {
					if (blogDetail.getFavorite() == 1) {
						res = ac.delFavorite(uid, blogId,
								FavoriteList.TYPE_BLOG);
					} else {
						res = ac.addFavorite(uid, blogId,
								FavoriteList.TYPE_BLOG);
					}
					msg.what = 1;
					msg.obj = res;
				} catch (AppException e) {
					e.printStackTrace();
					msg.what = -1;
					msg.obj = e;
				}
				handler.sendMessage(msg);
			}
		}.start();
	}

}
